<template>
  <el-row>
    <el-col :push="1" :span="3">
      <el-input v-model="FindProductForm.productName" style="width: 100%;" placeholder="请输入产品名字" @change="handleChangeproductName" />
    </el-col>

    <el-col :push="2" :span="4">
      <el-select v-model="FindProductForm.typeId" placeholder="请选择商品类型" @change="handleChangeproductType" style="width: 100%;">
        <el-option
          v-for="item in ProductType"
          :key="item.typeId"
          :label="item.typeName"
          :value="item.typeId"
        />
      </el-select>
    </el-col>

    <el-col :push="3" :span="4">
      <el-select v-model="FindProductForm.typeName" placeholder="请选择商品类型名称" @change="handleChangeproductType" style="width: 100%;">
        <el-option
          v-for="item in ProductType"
          :key="item.typeName"
          :label="item.typeName"
          :value="item.typeName"
        />
      </el-select>
    </el-col>

    <el-col :push="13" :span="2">
      <el-button type="text" @click="addproducttable">添加商品</el-button>
    </el-col>
  </el-row>

  <div class="product-list">
    <!-- 商品表格 -->
    <el-table :data="productList" style="width: 100%">
      <el-table-column prop="productId" label="产品ID" width="180"></el-table-column>
      <el-table-column prop="productName" label="产品名称" width="180"></el-table-column>
      <el-table-column prop="productPrice" label="价格" sortable></el-table-column>
      <el-table-column prop="typeName" label="类型名称"></el-table-column>
      <el-table-column prop="number" label="库存数量"></el-table-column>
      <el-table-column prop="describe" label="描述"></el-table-column>
      <el-table-column label="图片" width="150">
        <template #default="scope">
          <img :src="scope.row.picture" alt="Product Image" class="product-image" />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="260">
        <template #default="scope"> 
          <el-button type="text" v-show="scope.row.productState === 0" @click="UnShelvesProduct(scope.row)">下架</el-button>
          <el-button type="text" v-show="scope.row.productState === 1" @click="shelvesProduct(scope.row)">上架</el-button>
          <el-button type="text" @click="modify(scope.row)">修改</el-button>
          <el-button type="text" @click="deletes(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加商品对话框 -->
    <el-dialog v-model="isShow" title="添加商品" width="500">
      <span>
        <el-row>
          <el-col :span="14">
            <el-form-item label="商品名称">
              <el-input v-model="InsertNewProductForm.productName" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="商品价格">
              <el-input-number v-model="InsertNewProductForm.productPrice" :min="0" placeholder="请输入商品价格"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="商品类型ID">
              <el-select v-model="InsertNewProductForm.typeId" placeholder="请选择商品类型ID" style="width: 100%;">
                <el-option
                  v-for="item in ProductType"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="商品类型名称">
              <el-select v-model="InsertNewProductForm.typeName" placeholder="请选择商品类型名称" style="width: 100%;">
                <el-option
                  v-for="item in ProductType"
                  :key="item.typeName"
                  :label="item.typeName"
                  :value="item.typeName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="库存数量">
              <el-input-number v-model="InsertNewProductForm.number" :min="0" placeholder="请输入库存数量"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="商品所属者">
              <el-select v-model="InsertNewProductForm.productOwner" placeholder="请输入商品所属者" style="width: 100%;">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="商品描述">
              <el-input type="textarea" v-model="InsertNewProductForm.describe" placeholder="请输入商品描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-upload
            class="avatar-uploader"
            action="http://localhost:80/product/productTable/uploadPicture"
            :show-file-list="false"
            :headers="uploadHeaders"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="InsertNewProductForm.picture" :src="InsertNewProductForm.picture" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-row>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="text" @click="isShow = false">取消</el-button>
          <el-button type="text"  @click="add">确认添加</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改商品对话框 -->
    <el-dialog v-model="isShow1" title="修改商品" width="500">
      <span>
        <el-button type="text" @click="jiakucun">加库存</el-button>
        <el-button type="text" @click="jiashaokucun">减库存</el-button>
        <el-button type="text" @click="changeProductPrice">修改价格</el-button>
        <el-button type="text" @click="changeDescription">修改描述</el-button>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="text" @click="isShow1 = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="FindProductForm.pageForm.pageNo"
      :page-sizes="[2, 4, 8, 10]"
      :page-size.sync="FindProductForm.pageForm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  name: 'ProductList',
  data() {
    return {
      token: localStorage.getItem('token') || '',
      productList: [],
      total: 0,
      FindProductForm: {
        pageForm: {
          pageNo: null,
          pageSize: null
        },
        productName: null,
        typeId: null,
        typeName: null,
        productState: null
      },
      ProductType: {},
      options: [
        { value: '0', label: '上架' },
        { value: '1', label: '下架' }
      ],
      CollectProductForm: {
        productId: 0,
        userId: null
      },
      isShow: false,
      InsertNewProductForm: {
        productName: null,
        productPrice: null,
        typeId: null,
        typeName: null,
        number: null,
        productOwner: '平台',
        describe: null,
        picture: null,
      },
      productId: 0,
      isShow1: false,
      ChangeProductNumForm: {
        productId: 0,
        num: 0,
      },
      Exhibition1: false,
      Exhibition2: false,
      Exhibition3: false,
      Exhibition4: false,
      ChangeProductPriceForm: {
        productId: 0,
        productPrice: 0,
      },
      ChangeProductDescriptionForm: {
        describe: null,
        productId: 0,
      }
    };
  },
  methods: {
    deletes(obj) {
      this.productId = obj.productId;
      this.$http.delete('/product/productTable/deleteProductById', { params: { productId: this.productId } }).then(resp => {
        this.fetchProducts();
        alert(resp.data.message);
      });
    },
    ChangeProductDescription() {
      this.$http.put('/product/productTable/changeProductDescription', this.ChangeProductDescriptionForm).then(resp => {
        this.ChangeProductDescriptionForm.describe = null;
        this.ChangeProductDescriptionForm.productId = 0;
        this.Exhibition4 = false;
        this.fetchProducts();
        alert(resp.data.message);
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    changeDescription() {
      this.Exhibition4 = true;
      this.isShow1 = false;
    },
    ChangeProductPrice() {
      this.$http.put('/product/productTable/changeProductPrice', this.ChangeProductPriceForm).then(resp => {
        this.ChangeProductPriceForm.productId = 0;
        this.ChangeProductPriceForm.productPrice = 0;
        this.Exhibition3 = false;
        this.fetchProducts();
        alert(resp.data.message);
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    changeProductPrice() {
      this.Exhibition3 = true;
      this.isShow1 = false;
    },
    jianskucun() {
      this.$http.put('/product/productTable/decreaseProductNum', this.ChangeProductNumForm).then(resp => {
        this.ChangeProductNumForm.num = 0;
        this.ChangeProductNumForm.productId = 0;
        this.Exhibition2 = false;
        this.fetchProducts();
        alert(resp.data.message);
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    jiashaokucun() {
      this.Exhibition2 = true;
      this.isShow1 = false;
    },
    addkucun() {
      this.$http.put('/product/productTable/addProductNum', this.ChangeProductNumForm).then(resp => {
        this.ChangeProductNumForm.num = 0;
        this.ChangeProductNumForm.productId = 0;
        this.Exhibition1 = false;
        this.fetchProducts();
        alert(resp.data.message);
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    jiakucun() {
      this.Exhibition1 = true;
      this.isShow1 = false;
    },
    modify(obj) {
      this.isShow1 = true;
      this.ChangeProductNumForm.productId = obj.productId;
      this.ChangeProductPriceForm.productId = obj.productId;
      this.ChangeProductDescriptionForm.productId = obj.productId;
    },
    shelvesProduct(obj) {
      this.productId = obj.productId;
      let data = new FormData();
      data.append("productId", this.productId);
      this.$http.put('/product/productTable/shelvesProduct', data).then(resp => {
        this.fetchProducts();
        alert(resp.data.message);
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    UnShelvesProduct(obj) {
      this.productId = obj.productId;
      let data = new FormData();
      data.append("productId", this.productId);
      this.$http.put('/product/productTable/UnShelvesProduct', data).then(resp => {
        this.fetchProducts();
        alert(resp.data.message);
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    add() {
      this.$http.post('/product/productTable/addNewProduct', this.InsertNewProductForm).then(resp => {
        this.isShow = false;
        this.InsertNewProductForm.productName = null;
        this.InsertNewProductForm.productPrice = null;
        this.InsertNewProductForm.typeId = null;
        this.InsertNewProductForm.typeName = null;
        this.InsertNewProductForm.number = null;
        this.InsertNewProductForm.productOwner = null;
        this.InsertNewProductForm.describe = null;
        this.InsertNewProductForm.picture = null;

        alert(resp.data.message);
        this.fetchProducts();
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    uploadHeaders() {
      return {
        'token': this.token,
      };
    },
    handleAvatarSuccess2(response, file, fileList) {
      this.InsertNewProductForm.picture = response.data;
    },
    addproducttable() {
      this.isShow = true;
    },
    addcollectProduct(obj) {
      this.CollectProductForm.productId = obj.productId;
      this.$http.post('/product/productTable/collectProduct', this.CollectProductForm).then(resp => {
        alert(resp.data.message);
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    changeproductState() {
      this.FindProductForm.pageForm.pageNo = 1;
      this.fetchProducts();
    },
    handleChangeproductType() {
      this.FindProductForm.pageForm.pageNo = 1;
      this.fetchProducts();
    },
    handleChangeproductName() {
      this.FindProductForm.pageForm.pageNo = 1;
      this.fetchProducts();
    },
    fetchProducts() {
      const params = this.buildParams();

      this.$http.get('/product/productTable/findProduct', { params })
        .then(resp => {
          if (resp.data.success) {
            const data = resp.data.data;
            this.productList = data.list || [];
            this.total = data.total || 0;
          } else {
            console.error('获取商品列表失败:', resp.data.message);
          }
        })
        .catch(error => {
          console.error('获取商品列表失败:', error);
        });
    },
    buildParams() {
      return {
        'pageForm.pageNo': this.FindProductForm.pageForm.pageNo,
        'pageForm.pageSize': this.FindProductForm.pageForm.pageSize,
        productName: this.FindProductForm.productName,
        typeId: this.FindProductForm.typeId,
        typeName: this.FindProductForm.typeName,
        productState: this.FindProductForm.productState
      };
    },
    handleSizeChange(newSize) {
      this.FindProductForm.pageForm.pageSize = newSize;
      this.fetchProducts();
    },
    handleCurrentChange(newPage) {
      this.FindProductForm.pageForm.pageNo = newPage;
      this.fetchProducts();
    },
    getProductTypeList() {
      this.$http.get('/product/productType/selectProductType')
        .then(resp => {
          this.ProductType = resp.data.data;
        }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    }
  },
  created() {
    this.fetchProducts();
    this.getProductTypeList();
  }
};
</script>

<style scoped>
.product-list {
  margin: 20px;
}

.product-image {
  max-width: 100%;
  height: auto;
  display: block;
}

/* 输入框和选择框样式 */
.el-input,
.el-select {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  transition: border-color 0.3s;
}

.el-input:focus,
.el-select:focus {
  border-color: #409eff; /* 输入框聚焦时的边框颜色 */
}

/* 按钮样式 */
.el-button {
  margin: 5px 0; /* 按钮间距 */
  border-radius: 4px; /* 按钮圆角 */
}

.el-button[type="text"] {
  color: #409eff; /* 明显的文本按钮颜色 */
}

/* 表格样式 */
.el-table {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden; /* 为表格添加圆角 */
}

.el-table th {
  background-color: #f5f7fa; /* 表头背景色 */
  color: #606266; /* 表头文字颜色 */
}

/* 响应式样式 */
@media (max-width: 768px) {
  .product-list {
    margin: 10px;
  }

  .el-row {
    flex-direction: column; /* 小屏幕上垂直排列 */
  }

  .el-col {
    margin-bottom: 10px; /* 元素间距 */
  }

  .el-input,
  .el-select {
    width: 100%; /* 输入框全宽 */
  }

  .el-button {
    width: 100%; /* 按钮全宽 */
  }
}
</style>